package net.qunzhi.modules.weixin.service;

import com.alibaba.fastjson.JSON;
import net.qunzhi.common.utils.Constant;
import net.qunzhi.common.utils.DateUtils;
import net.qunzhi.config.WaterNetworkConfig;
import net.qunzhi.modules.app.dto.WXLogDto;
import net.qunzhi.modules.cms.entity.TbMsgWxLogEntity;
import net.qunzhi.modules.cms.service.TbMsgWxLogService;
import net.qunzhi.modules.weixin.config.WxMpProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微信模板消息推送
 * Created by lsd
 * 2019-07-18 22:57
 */
@Slf4j
@Service
public class PushWxMessageServiceImpl implements PushWxMessageService {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private TbMsgWxLogService tbMsgWxLogService;
    @Autowired
    private WxMpProperties wxMpProperties;
    private static String hostName;

    @PostConstruct
    public void init() {
        hostName = wxMpProperties.getConfigs().get(0).getHostName();
    }

    @Override
    public void sendAlarmRemind(String openId, WXLogDto data, Integer id) {
        String templateId = "Ys9DdyTs8uwnjaMsckB2BQgH-dw3syq_roUnLRhJYMc";//客户服务器
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateId);
        templateMessage.setToUser(openId);
        String toUrl = "http://" + hostName + "/warningdetails?id="+ id;
        templateMessage.setUrl(toUrl);
        List<WxMpTemplateData> templateData = Arrays.asList(
                new WxMpTemplateData("first", data.getTitle()),
                new WxMpTemplateData("keyword1", data.getCreateTime()),
                new WxMpTemplateData("keyword2", data.getContent()),
                new WxMpTemplateData("remark", "点击查看详情")
        );
        templateMessage.setData(templateData);
        // 保存微信消息记录
        sendAndSaveWxLog(openId, Constant.MsgWxLogType.ALARM_MSG, templateMessage);
    }

    @Override
    public void sendAndSaveWxLog(String openId, Constant.MsgWxLogType msgType, WxMpTemplateMessage templateMessage) {
        TbMsgWxLogEntity wxLogEntity = TbMsgWxLogEntity.builder()
                .content(JSON.toJSONString(templateMessage))
                .openId(openId)
                .type(msgType.getValue())
                .createTime(LocalDateTime.now())
                .build();
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            wxLogEntity.setIsSuccess(Constant.ONE);
        } catch (WxErrorException e) {
            log.error("【微信模板消息】发送失败，{}", e.getMessage());
            wxLogEntity.setIsSuccess(Constant.ZERO);
            //TODO 是否进行重发？

        } finally {
            tbMsgWxLogService.save(wxLogEntity);
        }
    }

}
